package com.woniuxy.springsecurity.service.impl;

import com.woniuxy.springsecurity.entity.LoginUserDetails;
import com.woniuxy.springsecurity.entity.User;
import com.woniuxy.springsecurity.service.UserService;
import com.woniuxy.springsecurity.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @Author author
 * @Create 2023-10-26 16:52
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public String login(User user) {
        //用户名密码，校验通过，返回token
        //密码比较，不需要再去实现，底层认证器已经实现了
        //Object principal,     身份信息:用户名，用户对象
        // Object credentials，  凭证:密码
        //获取前端的用户名密码，封装成UsernamePasswordAuthenticationToken对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUname(), user.getPassword());
        //调用认证管理器的认证方法,认证失败底层自动抛异常
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证成功，返回值获取身份信息，就是LoginUserDetails对象
        LoginUserDetails userDetails = (LoginUserDetails) authenticate.getPrincipal();
        System.out.println("验证器验证通过，返回Principal身份信息:"+userDetails);
        //认证成功,生成token
        return JwtUtil.createRereshToken(userDetails.getUser().getUid()+"",user.getUname());
    }
}
